plotly

Tao Zou

2024-01-02

Plotting Using Dict

import plotly.graph_objects as go

figure_config = {'data': [{'type': 'bar',
                           'x': ['Mon', 'Tues', 'Wed'],
                           'y': [1, 2, 3],
                           'name': 'Bar Trace'},
                          {'type': 'scatter',
                           'x': ['Mon', 'Tues', 'Wed'],
                           'y': [1, 2, 3],
                           'name': 'Line Trace'}],
                 'layout': {'title': {'text': 'Temperatures',
                                      'x': 0.5,
                                      'font': {'color': 'red', 'size': 15}},
                            'width': 768,
                            'height': 474}}
fig = go.Figure(figure_config)
fig.update_xaxes(title_text='My X-axis Title', tickangle=0, tickfont=dict(family='Times New Roman', size=24, color='black'))
fig.update_yaxes(title_text='My Y-axis Title', tickfont=dict(family='Times New Roman', size=12, color='red'), 
                 range=[0, 6], tickvals=[0, 2, 4, 6])
fig.update_layout({'showlegend': True, 
                   'legend': {'title': 'Legend Title', 'x': 0.8, 'y': 0.8, 'bgcolor': 'rgb(246, 228, 129)', 'borderwidth': 10}})
my_annotation1 = {'x': 'Mon', 'y': 2, 'showarrow': True, 'arrowhead': 2,
                  'text': 'My annotation', 'font': {'size': 10, 'color': 'black'},
                  'bgcolor': 'rgb(255, 0, 0)'}
my_annotation2 = {'xref': 'paper', 'yref': 'paper', 'x': 0.5, 'y': 1.0, 'showarrow': False,
                  'text': 'You are <b>mine</b>', 'font': {'size': 18, 'color': 'red'},
                  'bgcolor': 'rgb(210, 213, 10)'}
fig.update_layout({'annotations': [my_annotation1, my_annotation2]})
fig.show()

Univariate Visualizations

Bar chart

import plotly.express as px
import pandas as pd

df = pd.DataFrame({'x': ['Mon', 'Tues', 'Wed'], 'y': [1, 2, 3]})
fig = px.bar(data_frame=df, x='x', y='y')
fig.update_layout(title='My Title', title_x=0.5,
                  xaxis_title='My X-axis Title',
                  yaxis_title='My Y-axis Title',
                  font=dict(family='Times New Roman', size=24, color='black'),
                  width=768, height=474)
fig.update_xaxes(tickangle=0, tickfont=dict(family='Times New Roman', size=24, color='black'))
fig.update_yaxes(tickfont=dict(family='Times New Roman', size=36, color='black'), range=[0, 6], tickvals=[0, 2, 4, 6])
fig.show()

Histogram

df = pd.DataFrame({'x': ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'], 'y': [1, 2, 3, 1, 2, 1, 1]})
fig = px.histogram(data_frame=df, x='y', nbins=3)
fig.update_layout(title='My Title', title_x=0.5,
                  xaxis_title='My X-axis Title',
                  yaxis_title='My Y-axis Title',
                  font=dict(family='Times New Roman', size=24, color='black'),
                  width=768, height=474)
fig.update_xaxes(tickangle=0, tickfont=dict(family='Times New Roman', size=24, color='black'))
fig.update_yaxes(tickfont=dict(family='Times New Roman', size=36, color='black'), range=[0, 6], tickvals=[0, 2, 4, 6])
fig.show()

Box plot

df = pd.DataFrame({'x': ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun', 'Day'], 'y': [1, 2, 3, 1, 2, 1, 1, 99]})
fig = px.box(df, y='y', hover_data=['x'])
fig.update_layout(title='My Title', title_x=0.5,
                  xaxis_title='My X-axis Title',
                  yaxis_title='My Y-axis Title',
                  font=dict(family='Times New Roman', size=24, color='black'),
                  width=768, height=474)
fig.update_yaxes(tickfont=dict(family='Times New Roman', size=36, color='black'), range=[0, 6], tickvals=[0, 2, 4, 6])

hover_data is used to show the names of outliers when hovering the mouse.

fig.show()

Scatter plot

df = pd.DataFrame({'x': [1, 2, 3, 4, 5, 6], 'y': [4, 5, 6, 3, 7, 1], 'class': ['class1', 'class2', 'class2', 'class2', 'class1', 'class1']})
fig = px.scatter(df, x='x', y='y', color='class', hover_data=['class'], hover_name='class', width=768, height=474)
fig.show()

Color

color_discrete_map

df = pd.DataFrame({'x': ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'], 'y': [1, 2, 3, 1, 2, 1, 1]})
fig = px.bar(data_frame=df, x='x', y='y',
             color_discrete_map={'Mon': 'rgb(0, 0, 128)', 'Tues': 'cornflowerblue', 'Wed': 'red',
                                 'Thurs': 'pink', 'Fri': '#FF7F50', 'Sat': 'black', 'Sun': 'green'}, color='x', width=768, height=474)
fig.show()

color_continuous_scale

df = pd.DataFrame({'x': ['Mon', 'Tues', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun'], 'y': [1, 2, 3, 1, 2, 1, 1]})
myscale = [('cornflowerblue'), ('red'), ('blue')]
fig = px.bar(data_frame=df, x='x', y='y',
             color_continuous_scale=myscale, color='y',
             width=768, height=474)
fig.show()

The color_continuous_scale can be self-designed color scale or built-in color scale such as viridis, plasma and inferno. Here are many built-in scale available: https://plotly.com/python/builtin-colorscales/.

When color_continuous_scale is set, the color must be continuous variable.

Bivariate Visualization

Heatmap

df = pd.DataFrame({'column1': [1, 2, 3, 4, 5, 6, 9], 'column2': [4, 32, 6, 7, 12, 0, -10],
                   'column3': [2, 5, 7, 1, 0, 20, 1], 'column4': [1, 2, 5, 1, 1, 1, 12]})
cor_df = df.corr(method='pearson')
fig = go.Figure(go.Heatmap(x=cor_df.columns, y=cor_df.columns, z=cor_df.values,
                           colorscale='viridis', zmin=-0.9, zmax=0.9))
fig.update_layout(width=768, height=474)
fig.show()

subplot

from plotly.subplots import make_subplots

df = pd.DataFrame({'x': [1, 2, 3, 1, 2, 6, 34, 8, 1, 2, 3, 10, 38, 1],
                   'y1': [1, 2, 4, 1, 45, 1, 23, 2, 1, 2, 2, 10, 1, 1],
                   'y2': [1, 21, 4, 1, 4, 1, 23, 12, 1, 20, 22, 10, 14, 11]})
fig = make_subplots(rows=2, cols=1, subplot_titles=['Sub_Title1', 'Sub_Title2'], shared_xaxes=True)
fig.add_trace(go.Scatter(x=df['x'], y=df['y1'], mode='markers+text', text=df['y1'], textposition='top center', name='my trace 1'), row=1, col=1)
fig.add_trace(go.Scatter(x=df['x'], y=df['y2'], mode='markers+text', text=df['y2'], textposition='top center', name='my trace 2'), row=2, col=1)
fig.update_layout(width=768, height=474)
fig.show()